package com.jlnk.stockdemo.utils;

import android.content.pm.PackageManager;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class PermissionUtils {

    // 请求权限的回调接口
    public interface PermissionCallback {
        void onPermissionGranted();
        void onPermissionDenied();
    }

    // 请求权限
    public static void requestPermission(AppCompatActivity activity, String permission, int requestCode, PermissionCallback callback) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查是否已经获取了权限
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                // 权限未被授予，请求权限
                ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
            } else {
                // 权限已被授予，回调onPermissionGranted
                callback.onPermissionGranted();
            }
        } else {
            // 在Android 6.0以下，不需要动态请求权限
            callback.onPermissionGranted();
        }
    }

    // 处理请求权限的结果
    public static void onRequestPermissionsResult(AppCompatActivity activity, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults, PermissionCallback callback) {
        if (requestCode == 100) { // 100是请求码
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                callback.onPermissionGranted();
            } else {
                callback.onPermissionDenied();
            }
        }
    }
}